package com.example.questionanswersystem.service;

import com.example.questionanswersystem.entity.Question;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class PdfService {

    public List<Question> parseQuestions(InputStream inputStream, String sourceFileName) throws IOException {
        List<Question> questions = new ArrayList<>();
        PDDocument document = PDDocument.load(inputStream);
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(document);
        document.close();

        // Regex to find questions and answers
        Pattern questionPattern = Pattern.compile("(?:(?:题目|\\d+[、．.])[:：\\s])(.*?)(?=(?:答案[:：]|题目[:：]|\\d+[、．.]|$))", Pattern.DOTALL);
        Pattern answerPattern = Pattern.compile("(?:答案[:：\\s])(.*?)(?=(?:题目[:：]|\\d+[、．.]|$))", Pattern.DOTALL);

        String[] blocks = text.split("(?=(?:题目[:：]|\\d+[、．.]))");

        for (String block : blocks) {
            Matcher questionMatcher = questionPattern.matcher(block);
            Matcher answerMatcher = answerPattern.matcher(block);

            if (questionMatcher.find() && answerMatcher.find()) {
                Question question = new Question();
                question.setQuestionText(questionMatcher.group(1).trim());
                question.setAnswerText(answerMatcher.group(1).trim());
                question.setSourceFile(sourceFileName);
                questions.add(question);
            }
        }
        return questions;
    }
} 